import { RespCodeEnum } from "../enum";

interface BaseRespData<T = any> {
	code : number;
	data : T;
	msg : string;
}


export const handlerLogin = (hasLogin?:boolean,onSuccess?:()=>void) => {
	const token = uni.getStorageSync('token')
	if (!token || hasLogin) {
		uni.login({
			provider: "weixin",
			success: (options) => {
				const {
					code
				} = options
				uni.getUserInfo({
					provider: 'weixin',
					success: function (infoRes) {
						const useInfo = infoRes.userInfo
						http.post('/user/login', {
							code,
							avatarUrl: useInfo.avatarUrl,
							nickName: useInfo.nickName,
						}).then(res => {
							const token = res.data.token;
							uni.setStorageSync('token', token)
							uni.showToast({
								title: "授权成功",
								icon: "success"
							})
							onSuccess?.()
						}).catch((e) => {
							uni.showToast({
								title: "授权失败",
								icon: 'fail'
							})
						})
					},
					fail() {
						uni.showToast({
							title: "登录失败",
							icon: "fail"
						})
					}
				});

			},
			fail(error) {
				console.log("授权失败", error)
				uni.hideLoading()
			}
		})
	}

}


class Http {
	getInitConfig() {
		const token = uni.getStorageSync('token')
		const config : Record<string, any> = {
			header: {

			}
		}
		if (token) config.header.Authorization = `${token}`
		return config
	}

	handleResponse(resp : UniApp.RequestSuccessCallbackResult, reslove, reject,reasonCallback) {
		const { statusCode, errMsg, data } = resp
		if (statusCode === 200) {
			const { code, msg } = data as any
			if ([RespCodeEnum.SUCCESS, RespCodeEnum.SUCCESS_V2].includes(code)) {
				reslove(data)
			} else if (code === RespCodeEnum.JWT_CODE) {
				// TODO 权限失效，需要重新登录
				handlerLogin(true,reasonCallback)
			}
			else {
				uni.showToast({
					title: msg ?? "访问出现异常"
				})
				reject({
					code: statusCode,
					msg: msg ?? "访问出现异常",
					errMsg
				})
			}
		} else {
			reject({
				code: statusCode,
				msg: '服务调用异常！',
				errMsg
			})
		}
	}

	// 封装请求方法
	get<T = any>(url, params = {}, options = {}) {
		// uni.showLoading({ title: '加载中', mask: true })
		return new Promise<BaseRespData<T>>(async (reslove, reject) => {
			try {
				const config = this.getInitConfig()
				if (!Object.keys(config).length) return;
				 const resp = await uni.request({
					url: `http://localhost:8083/user${url}`,
					method: 'GET',
					data: params,
					...config,
					...options,
				})
				// uni.hideLoading()
				this.handleResponse(resp, reslove, reject,()=>this.get(url,params,options))
			} catch (e) {
				console.log(e);
				// uni.hideLoading()
				uni.showToast({ title: `逻辑内部错误: ${e}`, icon: "error" })
				reject(e)
			}
		})
	}

	post<T = any>(url, data = {}, options = {}) {
		// uni.showLoading({ title: '加载中', mask: true })
		return new Promise<BaseRespData<T>>(async (reslove, reject) => {
			try {
				const config = this.getInitConfig()
				if (!Object.keys(config).length) return;
				const resp = await uni.request({
					url: `http://localhost:8083/user${url}`,
					method: 'POST',
					data,
					...config,
					...options,
				})
				// uni.hideLoading()
				this.handleResponse(resp, reslove, reject,()=>this.post(url,data,options))
			} catch (e) {
				console.log(e);
				// uni.hideLoading()
				uni.showToast({ title: `逻辑内部错误: ${e}`, icon: "error" })
				reject(e)
			}
		})
	}
}

const http = new Http();
export default http;